﻿using AI.Common;
using AI.Demo.RoomsAnalyzeTool.Models;
using AI.Demo.RoomsAnalyzeTool.Similarity;
using GoogleSheetsWrapper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AI.Demo.RoomsAnalyzeTool
{
    internal class AnalyzeHistoryDataService
    {
        private bool _isDataLoaded;
        private GSheetRepository? _prodCPRRepository;
        private CrashSimilarityService? _similarityService;

        public List<GSheetRecord> ProdCPRRecords { get; set; } = new();

        public async Task LoadGoogleSheetData()
        {
            Console.WriteLine("--------------------------------------------------");
            Logger.WriteLine("Start load SCP all data.");
            var serviceAccount = "managegooglesheet@airy-period-411505.iam.gserviceaccount.com";

            // 使用绝对路径，避免工作目录差异
            string resourceName = Path.Combine(AppContext.BaseDirectory, "Resources", "airy-period-411505-39b2d3d35245.json");
            if (!File.Exists(resourceName))
            {
                throw new FileNotFoundException("凭证文件不存在: " + resourceName);
            }

            string jsonCredsContent;
            try
            {
                jsonCredsContent = await File.ReadAllTextAsync(resourceName);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("读取凭证文件失败: " + ex.Message, ex);
            }

            InitializeProductionData(serviceAccount, jsonCredsContent);
            _isDataLoaded = true;
            Logger.WriteLine("Finish load SCP all data.");
            Console.WriteLine("--------------------------------------------------");
        }

        private void InitializeProductionData(string serviceAccount, string jsonCredsContent)
        {
            Logger.WriteLine("Start load SCP Glip data.");
            const string GoogleSpreadSheetId = "1coAY6zUuRDWfWF45GMnHAPu8Ht6RpiYXuyJANLHWbZ0";
            const string TabName = "Other crash";
            var sheetHelper = new SheetHelper<GSheetRecord>(GoogleSpreadSheetId, serviceAccount, TabName);
            sheetHelper.Init(jsonCredsContent);

            var repoConfig = new BaseRepositoryConfiguration
            {
                HasHeaderRow = true,
                HeaderRowOffset = 0,
                DataTableRowOffset = 0
            };

            _prodCPRRepository = new GSheetRepository(sheetHelper, repoConfig);
            ProdCPRRecords = _prodCPRRepository.GetAllRecords();
            Logger.WriteLine($"Finish load SCP Glip data, count:{ProdCPRRecords.Count}");
        }

        /// <summary>
        /// Initialize AI similarity index with current loaded records.
        /// </summary>
        public async Task InitializeSimilarityAsync(ChatHelper chatHelper, CancellationToken ct = default)
        {
            if (!_isDataLoaded) throw new InvalidOperationException("数据尚未加载");
            _similarityService ??= new CrashSimilarityService(chatHelper);
            await _similarityService.InitializeAsync(ProdCPRRecords, ct);
            Logger.WriteLine("AI 相似度索引初始化完成。");
        }

        /// <summary>
        /// Query similar incident by providing new crash info.
        /// </summary>
        public async Task<QueryResult> QuerySimilarAsync(string crashStack, string device, string? clientVersion = null, int topN = 1, double threshold = 0.35, CancellationToken ct = default)
        {
            if (_similarityService == null) throw new InvalidOperationException("尚未初始化相似度服务");
            return await _similarityService.QueryAsync(crashStack, device, clientVersion, topN, threshold, ct);
        }

        /// <summary>
        /// Run automated evaluation harness (local similarity only) and return JSON string result.
        /// </summary>
        public async Task<string> EvaluateSimilarityAsync(int sampleSize = 50)
        {
            if (!_isDataLoaded) throw new InvalidOperationException("数据尚未加载");
            var summary = await CrashSimilarityTestHarness.RunAsync(ProdCPRRecords, sampleSize: sampleSize);
            return CrashSimilarityTestHarness.ToJson(summary);
        }
    }
}